<template>
  <div class="container">
    <div class="button-bar">
      <span class="buttons" v-if="tableConfig.buttons!=null">
        <el-button
            v-for="(item, index) in tableConfig.buttons"
            :key="index"
            type="primary"
            plain
            size="default"
            class="mainBtn"
            @click="click(item.click, item)"
            :icon="item.icon"
            secondBtn
        >
          {{ item.name }}
        </el-button>
      </span>
      <div :class="[tableConfig.buttons!=null ? 'searchHeader' : 'searchHeader1']">
        <span class="condition" v-if="condition.length>0">
          <!-- <el-icon v-if="condition !== undefined && condition.length > 0">
          <Search />
        </el-icon> -->
          <span>搜索条件:</span>
          <el-tag
              v-for="(item, index) in condition"
              :key="index"
              closable
              effect="dark"
              @close="handleTagClose(index)"
          >
            {{ item.name }}：{{ item.label }}
          </el-tag>
          <span
              style="
              display: inline-block;
              margin-left: 16px;
              font-size: 14px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #3370ff;
              cursor: pointer;
            " @click="reset"
          >重置</span>
        </span>
        <span class="condition" v-else>
          <span>搜索条件: 无</span>
        </span>
        <el-button
            v-if="tableConfig.selectColumn"
            type="primary"
            plain
            size="default"
            class="mainBtn"
            icon="Filter"
            @click="openDrawer()"
        >表头筛选</el-button
        >
      </div>
    </div>

    <el-table
        class="tableContainer"
        size="default"
        style="width: 100%"
        v-loading="tableLoading"
        :data="tableData"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
        :height="tableHeight"
        :header-cell-style="{
        background: '#F2F4F7',
        textAlign: 'left',
        color: '#333333',
        padding: '4px 0px 4px 0px',
        fontSize: '14px',
        fontFamily: 'PingFangSC-Regular, PingFang SC',
        fontWeight: 400,
      }"
        :cell-style="{ padding: '5px 0px 5px 0px' }"
    >
      <el-table-column
          v-if="tableConfig.multiSelection === '1'"
          label="全选"
          type="selection"
          width="30"
          align="center"
      >
      </el-table-column>
      <el-table-column
          v-if="tableConfig.ifIndex === '1'"
          label="序号"
          width="60"
          fixed
          align="center"
          type="index"
          :index="
          (index) => {
            return index + 1 + parseInt(page.rowFrom);
          }
        "
      >
      </el-table-column>
      <el-table-column
          v-for="(columnItem, index) in tableConfig.columnData.filter((item) => {
          return item.visible == '1';
        })"
          :align="columnItem.align"
          :width="columnItem.width"
          :min-width="columnItem.min_width"
          :key="index"
          :fixed="columnItem.fixed"
          show-overflow-tooltip
      >
        <template #header>
          {{ columnItem.name }}
          <table-header-popover
              v-if="columnItem.is_condition"
              :columnType="columnItem.query_column_type"
              :columnCode="columnItem.code"
              :columnValue="condition[columnItem.code]"
              :dataUrl="columnItem.data_url"
              @search="changeCondition"
          />
          <table-header-sort
              v-if="columnItem.sort"
              :columnCode="columnItem.code"
              @changeSort="changeSort"
          />
        </template>
        <template #default="scope">
          <!--链接-->
          <span
              v-if="
              columnItem.click !== undefined && columnItem.click.length >= 1
            "
          >
            <!--链接+图片-->
            <el-image
                v-if="columnItem.image_code != undefined"
                style="width: 32px; height: 32px"
                :src="scope.row[columnItem.image_code]"
                fit="contain"
            />
            <el-link
                type="primary"
                @click="click(columnItem.click, scope.row, columnItem.link_url)"
            >{{ scope.row[columnItem.code] }}
            </el-link>
          </span>
          <!--图片-->
          <span v-else-if="columnItem.table_column_type == 'image'">
            <el-image
                style="width: 32px; height: 32px"
                :src="scope.row[columnItem.code]"
                fit="contain"
            />
          </span>
          <!--按钮-->
          <!--选项-->
          <span v-else-if="columnItem.options !== undefined">
            {{ transcode(columnItem.options, scope.row[columnItem.code]) }}
          </span>
          <!--文字-->
          <span v-else>
            <!--文字+图标-->
            <component
                v-if="columnItem.icons !== undefined"
                :is="columnItem.icons[scope.row[columnItem.icon_code]]"
                style="width: 16px; height: 16px"
            />
            <!--文字+图片-->
            <el-image
                v-if="columnItem.image_code != undefined"
                style="width: 32px; height: 32px"
                :src="scope.row[columnItem.image_code]"
                fit="contain"
            />
            <!--显示转码-->
            <template v-if="columnItem.show_code !== undefined">{{
                scope.row[columnItem.show_code]
              }}</template>
            <!--文字-->
            <!--文字-->
            <template v-else>
                    <template v-if="columnItem.dataTypeFormat!== undefined && moment(scope.row[columnItem.code]).tz('Asia/Shanghai').format(columnItem.dataTypeFormat)!='Invalid date'">
                       {{moment(scope.row[columnItem.code]).tz("Asia/Shanghai").format(columnItem.dataTypeFormat)}}
                    </template>
                    <template v-else-if="scope.row[columnItem.code]==undefined">
                     ---
                    </template>
                    <template v-else>
                      {{ scope.row[columnItem.code] }}
                    </template>
            </template>
          </span>
        </template>
      </el-table-column>

      <el-table-column
          v-if="
          tableConfig.operations !== undefined &&
          tableConfig.operations !== null &&
          tableConfig.operations.length > 0
        "
          label="操作"
          :width="tableConfig.operationWidth"
          fixed="right"
      >
        <template #default="scope">
          <div v-for="(buttonItem, index) in tableConfig.operations.filter(
              (item) => {
                return item.is_more == '0';
              }
            )"
               style="display: inline-block;"
          >
            <!-- 根据条件是否显示 -->
            <slot v-if="buttonItem.show_by_code  && buttonItem.when_value ">
              <slot v-if="buttonItem.when_value.split(',').includes(scope.row[[buttonItem.show_by_code]]) ">
                <el-link
                  :underline="false"
                  :key="index"
                  :type="buttonItem.type !== null ? buttonItem.type : 'primary'"
                  @click="click(buttonItem.click, scope.row, buttonItem.link_url)"
                >
                  <component v-if="buttonItem.icon !== null" :is="buttonItem.icon" style="width:16px; height:16px;" />
                  {{ buttonItem.name }}
                </el-link>
              </slot>
            </slot>
            <!-- 显示按钮 -->
            <slot v-else-if="buttonItem.name !== null">
              <el-link
                :underline="false"
                :key="index"
                :type="buttonItem.type !== null ? buttonItem.type : 'primary'"
                @click="click(buttonItem.click, scope.row, buttonItem.link_url)"
              >
                <component
                  v-if="buttonItem.icon !== null"
                  :is="buttonItem.icon"
                  style="width: 16px; height: 16px"
                />
                {{ buttonItem.name }}
              </el-link>
            </slot>
            <!-- 动态按钮名称 -->
            <slot v-else-if="buttonItem.name_by_option !== null">
              <el-link
                :underline="false"
                :key="index"
                :type="buttonItem.type !== null ? buttonItem.type : 'primary'"
                @click="click(buttonItem.click, scope.row, buttonItem.link_url)"
              >
                <component
                  :is="buttonItem.icons[scope.row[buttonItem.name_by_option]]"
                  style="width: 16px; height: 16px"
                />
                {{ buttonItem.options[scope.row[buttonItem.name_by_option]] }}
              </el-link>
            </slot>
          </div>
          <!-- 下拉菜单 -->
          <el-dropdown
              v-if="
              tableConfig.operations !== null &&
              tableConfig.operations.filter((item) => {
                return item.is_more == '1' && item.when_value.split(',').includes(scope.row[[item.show_by_code]])
              }).length > 0
            "
              @command="handleCommand"
          >
            <span class="eldropdown">…</span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                    v-for="(item, index) in tableConfig.operations.filter(
                    (item) => {
                      if(item.show_by_code != null && item.when_value != null) {
                             if(item.is_more == '1' && item.when_value.split(',').includes(scope.row[[item.show_by_code]])) return true;
                      } else { return item.is_more == '1'}
                    }
                  )"
                    :key="index"
                    :icon="item.icon"
                    :command="{
                    event: item.click,
                    item: scope.row,
                    link_url: item.link_url,
                  }"
                >
                  {{ item.name }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        class="pagination"
        v-if="tableConfig.ifPage === '1'"
        v-model:currentPage="page.pangeNo"
        v-model:page-size="page.pageSize"
        :page-sizes="[10, 15, 20, 30, 50]"
        layout="total,sizes,->,prev,pager,next,jumper"
        :total="page.rowCount"
        @current-change="changePage"
        @size-change="changePageSize"
        background
    />

    <el-drawer v-model="drawerVisible" title="选择字段" append-to-body>
      <div class="draBox">
        <el-form
            label-width="90px"
            :model="formLabelAlign"
            style="max-width: 460px"
        >
          <el-form-item label="表头搜索：">
            <el-input
                v-model="clname"
                placeholder="请输入您想查找的表头名称"
                :prefix-icon="Search"
            />
          </el-form-item>
        </el-form>
        <el-table
            :data="tableConfig.columnData.filter((item)=>{ return (item.visible || item.colvisible)  && (clname==undefined || item.name.indexOf(clname)>-1 )  ; })"
            :row-style="{ cursor: 'move' }"
            row-key="code"
            :header-cell-style="{
            background: '#F2F4F7',
            textAlign: 'left',
            color: '#333333',
            padding: '4px 0px 4px 0px',
            fontSize: '14px',
            fontFamily: 'PingFangSC-Regular, PingFang SC',
            fontWeight: 400,
          }"
            :cell-style="{ padding: '0px 0px 0px 0px' }"
        >
          <el-table-column label="选择" width="80" align="center">
            <template #default="scope">
              <el-checkbox
                  v-model="scope.row.visible"
                  true-label="1"
                  false-label="0"
                  size="large"
                  :disabled="scope.row.fixedColumn == '1'"
              />
            </template>
          </el-table-column>
          <el-table-column label="列名" prop="name" align="left">
          </el-table-column>
          <el-table-column label="操作" prop="operate" align="left">
            <template #default="scope" >
              <el-radio-group v-model="scope.row.fixed" size="small" v-if="scope.row.visible==true">
                <el-radio-button   label="left">固定</el-radio-button>
                <el-radio-button   label="false">取消</el-radio-button>
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--      <template #footer>
              <div style="flex: auto">
                <el-button class="secondBtn" @click="cancelClick">取消</el-button>
                <el-button type="primary" class="mainBtn" @click="confirmClick"
                  >保存</el-button
                >
              </div>
            </template>-->
    </el-drawer>
    <!--    <DrawerAssembly-->
    <!--      :dialogVisible="dialogInfo"-->
    <!--      @changeVi="changeVi"-->
    <!--    ></DrawerAssembly>-->
  </div>
</template>
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import Sortable from "sortablejs";
import tableHeaderSort from "../TableHeader/sort.vue";
import tableHeaderPopover from "../TableHeader/popover.vue";
import request from "@/utils/axios";
//import DrawerAssembly from "../DrawerAssembly/add.vue";
import { Search } from "@element-plus/icons-vue";
import moment  from "moment";
import 'moment-timezone';

const props = defineProps({
  tableConfig: Object,
  args: Object,
});
const emits = defineEmits([
  "add",
  "del",
  "edit",
  "event1",
  "event2",
  "event3",
  "event4",
  "event5",
  "event6",
  "event7",
  "event8",
  "event9",
  "event10",
]);
const formLabelAlign = reactive({
  type: "",
});

const tableData = ref([]); //表格数据
const tableLoading = ref(); //加载中状态
const tableHeight = ref(); //表格高度
const page = ref({ rowCount: 0, pageSize: 20, pageNo: 1, rowFrom: 0 }); //列表分页
const orderArr = ref([]); //排序条件
const selectedRow = ref([]); //选中行
const condition = ref([]); //查询条件
const drawerVisible = ref(false); //抽屉是否可见
const currentClick = ref(false);
const title = ref("固定表头");
const clname = ref(); //列选择的搜索

onMounted(() => {
  console.log("table mounted:", props.tableConfig);
  if (props.tableConfig.dataUrl) {
    loadData();
  }
  if (props.tableConfig.autosize === "1") {
    autosize();
  }
});
// 自动高度
const autosize = () => {
  let height = 80;
  if (props.tableConfig.heightMinus) {
    height = height + Number(props.tableConfig.heightMinus);
  }
  tableHeight.value = window.innerHeight - height;

  window.onresize = () => {
    tableHeight.value = window.innerHeight - height;
  };
};

// 加载数据
const loadData = () => {
  //console.log(props.tableConfig.dataUrl)
  tableLoading.value = true;
  request({
    url: props.tableConfig.dataUrl,
    method: "post",
    data: {
      condition: condition.value,
      sort: orderArr.value,
      page: page.value,
    },
  })
      .then((res) => {
        //console.log(res.data)
        tableData.value = res.data.ds1;
        if (res.data.ds1page) {
          page.value = res.data.ds1page;
        }
        tableLoading.value = false;
      })
      .catch((err) => {
        //console.log(err)
        ElMessage({
          showClose: true,
          message: "网络错误，请稍后再试。",
          type: "error",
          duration: 5000,
        });
        tableLoading.value = false;
      });
};

// 划出右侧抽屉
const openDrawer = () => {
  drawerVisible.value = true;
  setTimeout(() => {
    rowDrop();
  }, 1000);
};
//行拖拽
const rowDrop = () => {
  const tbody = document.querySelector(
      ".el-drawer__body .el-table__body-wrapper tbody"
  );
  Sortable.create(tbody, {
    onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex);

      const currRow = props.tableConfig.columnData.splice(oldIndex, 1)[0];
      props.tableConfig.columnData.splice(newIndex, 0, currRow);
      tableData.value = tableData.value;
    },
  });
};
// 点击触发方法: go打开窗口，其他执行父组件方法add,del,edit,event1...10
// const dialogInfo = reactive({
//   isShow: false,
//   title: "新增企业信息",
//   size: "634px",
// });
const click = (method, item, link_url) => {
  console.log(item, "++++++++++++++++++++++++++++++++++++++");
  // if (item.name == "新增") {
  //   dialogInfo.isShow = true;
  // }
  if (method == "go") {
    go(link_url, item);
  } else if (method == "exportExcel") {
    exportExcel();
  } else {
    emits(method, item);
  }
};
const changeVi = (val) => {
  dialogInfo.isShow = false;
};
const exportExcel = () => {
  request({
    url: "/query/" + props.tableConfig.code + "/download",
    method: "post",
    data: {
      condition: condition.value,
      sort: orderArr.value,
      page: page.value,
    },
    responseType: "blob",
  })
      .then((res) => {
        const elink = document.createElement("a");
        elink.download = props.tableConfig.code + ".xlsx";
        elink.style.display = "none";
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        const href = URL.createObjectURL(blob);
        elink.href = href;
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        window.URL.revokeObjectURL(href);
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          showClose: true,
          message: "网络错误，请稍后再试。",
          type: "error",
          duration: 5000,
        });
      });
};
// 跳转 "/design/form?code=member&id=id"
const go = (link_url, item) => {
  //console.log("url", link_url, item)
  let arr_url = link_url.split("?");
  if (arr_url.length == 1) {
    openWin(arr_url[0]);
  } else {
    let arr_arg = arr_url[1].split("&");
    //console.log(arr_arg)
    let args = {};
    for (let arg of arr_arg) {
      let arr_pair = arg.split("=");
      //console.log(arr_pair)
      args[arr_pair[0]] = item[arr_pair[1]];
    }
    //console.log(args)
    openWinWithParam(arr_url[0], args);
  }
};
const router = useRouter();
// 打开窗口
const openWin = (url) => {
  const { href } = router.resolve({
    path: url,
  });
  window.open(href, "_blank");
};
const openWinWithParam = (url, args) => {
  const { href } = router.resolve({
    path: url,
    query: args,
  });
  window.open(href, "_blank");
};
// 下拉菜单，更多操作
const handleCommand = (command) => {
  console.log(command.event, command.item, command.link_url);
  click(command.event, command.item, command.link_url);
};
// 表格选择行
const handleSelectionChange = (val) => {
  selectedRow.value = val;
  //console.log(selectedRow.value)
};
defineExpose({ loadData, selectedRow,condition,page,orderArr });
// 改变当前页
const changePage = (val) => {
  console.log(val);
  page.value.pageNo = val;
  loadData();
};
//改变当前页面
const changePageSize = (val) => {
  console.log(val)
  page.value.pageNo = 1
  loadData()
}
// 改变查询条件
const changeCondition = (val) => {
  let position = findInArr(condition.value, val.code);
  if (position > -1) {
    condition.value.splice(position, 1);
  }
  //tableConfig.columnData中找name
  val.name = findName(val.code);
  condition.value.push(val);
  console.log(condition.value);
  loadData();
};
const findName = (code) => {
  for (let item of props.tableConfig.columnData) {
    if (item.code == code) {
      return item.name;
    }
  }
  return "";
};
// 删除条件
const handleTagClose = (index) => {
  //console.log(index)
  condition.value.splice(index, 1);
  loadData();
};
// 改变排序条件
const changeSort = (code, val) => {
  let position = findInArr(orderArr.value, code);
  //console.log(position)
  if (position > -1) {
    orderArr.value.splice(position, 1);
  }
  if (val != "0") {
    orderArr.value.unshift({ code, val });
  }
  //console.log(orderArr.value)
  loadData();
};
// 查找在数组中的位置
const findInArr = (arr, code) => {
  let i = 0;
  for (let item of arr) {
    if (item.code == code) {
      return i;
    }
    i++;
  }
  return -1;
};
// 转码显示
const transcode = (options, value) => {
  for (const item of options) {
    if (item.value === value) {
      return item.label;
    }
  }
  return "";
};
//点击取消固定
const cancelTable = () => {
  currentClick.value = true;
  title.value = "取消固定";
  console.log("点击了");
};

const reset = () => {
  condition.value = [];
  loadData();
}
</script>
<style lang="scss" scoped>
@import "@/style/dynamicTable";
:deep(.el-link__inner) {
  font-size: 14px !important;
  font-family: MicrosoftYaHei !important;
  color: #3370ff !important;
}
:deep(.el-link__inner:hover) {
  color: #0d50ed !important;
}
:deep(.el-link__inner:active) {
  color: #0c45cd !important;
}
.active {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #e73c3c;
}
.btntitle {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #3370ff;
}
.searchHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
}
.searchHeader1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
:deep(.el-dropdown-menu__item) {
  color: #3370ff !important;
}
:deep(.el-dropdown-menu__item):hover {
  color: #0d50ed !important;
}
</style>
